package com.sdzee.meteocal.servlets;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




















import net.aksingh.owmjapis.DailyForecast;
import net.aksingh.owmjapis.OpenWeatherMap;
import net.aksingh.owmjapis.DailyForecast.Forecast;
import net.aksingh.owmjapis.DailyForecast.Forecast.Temperature;

import org.eclipse.persistence.exceptions.DatabaseException;
import org.eclipse.persistence.exceptions.EclipseLinkException;
import org.json.JSONException;

import com.sdzee.dao.*;

import model.*;


/**
 * Servlet implementation class PersonalPageServlet
 */
@WebServlet ("/personalPageServlet")
public class PersonalPageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static String EDIT = "/WEB-INF/NewEventEdit.jsp";
	private static String INSERT = "/WEB-INF/NewEvent.jsp";
	private static String LIST_EVENT = "/WEB-INF/PersonalPage.jsp";
	private static String NOTIFICATIONS = "/WEB-INF/Notification.jsp";
	@EJB
	private UserDaoEJB uDAO ;
	@EJB
	private InvitationDaoEJB iDAO ;
	@EJB
	private NotificationDaoEJB nDAO ;
	@EJB 
	private EventDaoEJB eDAO ;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PersonalPageServlet() {
        super();
        // TODO Auto-generated constructor stub
        uDAO=new UserDaoEJB() ;
        
    	iDAO=new InvitationDaoEJB() ;
    	
    	nDAO=new NotificationDaoEJB();
    	
        eDAO=new EventDaoEJB() ;
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String forward="";
        String action = request.getParameter("action");
        String pseudo = request.getParameter("pseudo");
        String EventId =request.getParameter("eventid");
        
        if (action.equalsIgnoreCase("delete")){
            int eventId = Integer.parseInt(EventId);
            eDAO.deleteEvent(eventId);
            forward = LIST_EVENT;
         //puntare direttamente all pagina personale..vedremmo dopo !
	    		
	    		//les deux tables de la page personelle
	    		List<Event> eventCreated = eDAO.findEventsCreator(pseudo);
	    		List<Event> invitationAccepted = iDAO.findInvitationAccepted(pseudo);
	    		
	    		//calcolo della temperautra in °F per ogni Event   	    		
  	    		Map<Event, Long> tempsMaxE = new HashMap<Event,Long>();   
  	    		Map<Event,Long> tempsMinE = new HashMap<Event,Long>();
  	    		Map<Event, Long> tempsMaxI = new HashMap<Event,Long>();  
  	    		Map<Event, Long> tempsMinI = new HashMap<Event,Long>();
            	
                for( Event item: eventCreated){     
  	    			
                	float vet[]= getTemp(item.getPlace());
                	
                	tempsMaxE.put(item,(long)vet[0]);   
                	tempsMinE.put(item,(long)vet[1]);                    
  	            }              
  	    		
                for( Event item: invitationAccepted){
  	    			
                    float vet[]= getTemp(item.getPlace());
                	         
                	 tempsMaxI.put(item,(long)vet[0]);                      
                	 tempsMinI.put(item,(long)vet[1]);    
                	 
  	            }
  	    		
  	    		//Temperatures
  	    		request.setAttribute("tempsMaxE", tempsMaxE);
  	    		request.setAttribute("tempsMinE", tempsMinE);
  	    		request.setAttribute("tempsMaxI", tempsMaxI);
  	    		request.setAttribute("tempsMinI", tempsMinI);
  	    		      
	    		
	    		
	    		//gestion du voyant de notifications
	    		List<Notification> notif = nDAO.findMyNotifications(pseudo);
	    		if(!notif.isEmpty()){
	    			String youHaveNewNotification = "you have some new NOTIFICATIONS, please read it !! <br> ";
	    			
	    					request.setAttribute("youHaveNewNotification", youHaveNewNotification);
    			
	    		}
	    		//fin gestion du voyant
	  	    		
	    		request.setAttribute("events", eventCreated);
	    		request.setAttribute("invitatedEvents", invitationAccepted);      
	    		
	    		//pour rester dans la contexte pseudo, je dois le faire suivre.
	    		request.setAttribute("pseudo", pseudo);
	    		       
	    		
	    		
	    		
	    		
	    		//this.getServletContext().getRequestDispatcher(forward).forward( request, response );
            
        } else if (action.equalsIgnoreCase("edit")){
            forward = EDIT;
            int eventId = Integer.parseInt(EventId);      
            
            String fdate = "mm/jj/yyyy";
            request.setAttribute("fdate", fdate);
            
            Event event = eDAO.getEventById(eventId);
            request.setAttribute("event", event);
            request.setAttribute("pseudo", pseudo);
        
        } else if(action.equalsIgnoreCase("insert")) {
            forward = INSERT;
            
            String fdate = "mm/jj/yyyy";
            request.setAttribute("fdate", fdate);
            
            request.setAttribute("pseudo", pseudo);
            List<String> list = uDAO.findAll();
            request.setAttribute("listToInvite", list);
        } else if(action.equalsIgnoreCase("notification")) {
        	// gestion des notifications
        	forward = NOTIFICATIONS;
        	List<Notification> notif = nDAO.findMyNotifications(pseudo);
        	List<Event> eventsProposed = new ArrayList<Event>();
    		List<String> messagesAlert_Invitation = new ArrayList<String>();
	    		
    		for(Notification item : notif){
	    			int id = item.getIdnotification();
	    			String ev = item.getEventAbout();
	    			String me = item.getMessageAlert_Invitation();
	    			String us = item.getUserDestinatore();
	    			
	    			//notification is a event
	    			if(!ev.equals("none")){ 
	    				eventsProposed.addAll(eDAO.findEventsForTheInvited(ev));
	    				//nDAO.move(id);
	    				}
	    		   //notification is message_alert
	    			if(!me.equals("none")){ 
	    				//afficher le message "me"
	    				messagesAlert_Invitation.add(me);
	    				//nDAO.move(id);
	    				}
	    			
	    		}
    		
    		request.setAttribute("pseudo", pseudo);
    		request.setAttribute("eventsProposed", eventsProposed);
    		request.setAttribute("messagesAlert_Invitation", messagesAlert_Invitation);
    		
        } else if (action.equalsIgnoreCase("deny")) {        	
        	 forward = NOTIFICATIONS;
        	 int eventId = Integer.parseInt(EventId);
        	 
        	 Event denyEvent = eDAO.getEventById(eventId);
        	 int idNotif = nDAO.getIdNotificatioByEventAbout(denyEvent.getName(), pseudo);
        	 nDAO.move(idNotif);
        	 
        	 List<Notification> notif = nDAO.findMyNotifications(pseudo);
         	 List<Event> eventsProposed = new ArrayList<Event>();
     		 List<String> messagesAlert_Invitation = new ArrayList<String>();
     		 
        	 // pullire notif prima du reaffichage
        	/* for(Notification item : notif ){
        		 if( item.getIdnotification() == eventId ) {  notif.remove(item); }
        	 }*/
        	 
        	 for(Notification item : notif){
	    			int id = item.getIdnotification();
	    			String ev = item.getEventAbout();
	    			String me = item.getMessageAlert_Invitation();
	    			String us = item.getUserDestinatore();
	    			
	    			//notification is a event
	    			if(!ev.equals("none")){ 
	    				eventsProposed.addAll(eDAO.findEventsForTheInvited(ev));
	    				//nDAO.move(id);
	    				}
	    		   //notification is message_alert
	    			if(!me.equals("none")){ 
	    				//afficher le message "me"
	    				messagesAlert_Invitation.add(me);
	    				//nDAO.move(id);
	    				}
	    		}
 		
 		request.setAttribute("pseudo", pseudo);
 		request.setAttribute("eventsProposed", eventsProposed);
 		request.setAttribute("messagesAlert_Invitation", messagesAlert_Invitation);
        	       	
        } else if (action.equalsIgnoreCase("accept")){
        	 
        	 forward = NOTIFICATIONS;
        	 int eventId = Integer.parseInt(EventId);
        	 Event denyEvent = eDAO.getEventById(eventId);
        	 int idNotif = nDAO.getIdNotificatioByEventAbout(denyEvent.getName(), pseudo);
        	 nDAO.move(idNotif);
        	 
        	 //Insertion dans Invitation
        	 Event eve = eDAO.getEventById(eventId); 
        	 String na = eve.getName();
        	 String invited = pseudo;
        	 String invitor = eve.getEventCreator();
        	 Invitation NewInvitation = new Invitation();
        	 NewInvitation.setEvent(na);
        	 NewInvitation.setInvited(invited);
        	 NewInvitation.setInvitor(invitor);
        	 iDAO.add(NewInvitation);
        	 
        	 //reafficher tout 
        	 List<Notification> notif = nDAO.findMyNotifications(pseudo);
         	 List<Event> eventsProposed = new ArrayList<Event>();
     		 List<String> messagesAlert_Invitation = new ArrayList<String>();
     		 
        	 // pullire notif prima du reaffichage
        	/* for(Notification item : notif ){
        		 if( item.getIdnotification() == eventId ) {  notif.remove(item); }
        	 }*/
        	 
        	 for(Notification item : notif){
	    			int id = item.getIdnotification();
	    			String ev = item.getEventAbout();
	    			String me = item.getMessageAlert_Invitation();
	    			String us = item.getUserDestinatore();
	    			
	    			//notification is a event
	    			if(!ev.equals("none")){ 
	    				eventsProposed.addAll(eDAO.findEventsForTheInvited(ev));
	    				//nDAO.move(id);
	    				}
	    		   //notification is message_alert
	    			if(!me.equals("none")){ 
	    				//afficher le message "me"
	    				messagesAlert_Invitation.add(me);
	    				//nDAO.move(id);
	    				}
	    		}
 		
 		request.setAttribute("pseudo", pseudo);
 		request.setAttribute("eventsProposed", eventsProposed);
 		request.setAttribute("messagesAlert_Invitation", messagesAlert_Invitation);
        	
        } else if (action.equalsIgnoreCase("messageRead")){
        	
        	 forward = NOTIFICATIONS;
        	 
        	
        	 
        	 List<Notification> notif = nDAO.findMyNotifications(pseudo);
         	 List<Event> eventsProposed = new ArrayList<Event>();
     		
 	    		
     		for(Notification item : notif){
 	    			int id = item.getIdnotification();	    			
 	    			String ev = item.getEventAbout();
 	    			String me = item.getMessageAlert_Invitation();
 	    			String us = item.getUserDestinatore();
 	    			
 	    			//notification is a event
 	    			if(!ev.equals("none")){ 
 	    				eventsProposed.addAll(eDAO.findEventsForTheInvited(ev));
 	    				//nDAO.move(id);
 	    				}
 	    			//supprimer tous les messages
 	    			if(!me.equals("none")){ 
	    				//afficher le message "me"
	    				//messagesAlert_Invitation.add(me);
	    				nDAO.move(id);
	    				}
 	    		   
 	    			
 	    		}
     		
     		request.setAttribute("pseudo", pseudo);
     		request.setAttribute("eventsProposed", eventsProposed);
     		
        	
        }else if (action.equalsIgnoreCase("finishReading")){
        	
        	 forward = LIST_EVENT;
             //puntare direttamente all pagina personale..vedremmo dopo !
    	    		
    	    		//les deux tables de la page personelle
    	    		List<Event> eventCreated = eDAO.findEventsCreator(pseudo);
    	    		List<Event> invitationAccepted = iDAO.findInvitationAccepted(pseudo);
    	    		
    	    		//calcolo della temperautra in °F per ogni Event   	    		
      	    		Map<Event, Long> tempsMaxE = new HashMap<Event,Long>();   
      	    		Map<Event,Long> tempsMinE = new HashMap<Event,Long>();
      	    		Map<Event, Long> tempsMaxI = new HashMap<Event,Long>();  
      	    		Map<Event, Long> tempsMinI = new HashMap<Event,Long>();
                	
                    for( Event item: eventCreated){     
      	    			
                    	float vet[]= getTemp(item.getPlace());
                    	
                    	tempsMaxE.put(item,(long)vet[0]);   
                    	tempsMinE.put(item,(long)vet[1]);                    
      	            }              
      	    		
                    for( Event item: invitationAccepted){
      	    			
                        float vet[]= getTemp(item.getPlace());
                    	         
                    	 tempsMaxI.put(item,(long)vet[0]);                      
                    	 tempsMinI.put(item,(long)vet[1]);    
                    	 
      	            }
      	    		
      	    		//Temperatures
      	    		request.setAttribute("tempsMaxE", tempsMaxE);
      	    		request.setAttribute("tempsMinE", tempsMinE);
      	    		request.setAttribute("tempsMaxI", tempsMaxI);
      	    		request.setAttribute("tempsMinI", tempsMinI);
      	    		
    	    		
    	    		
    	    		//gestion du voyant de notifications
    	    		List<Notification> notif = nDAO.findMyNotifications(pseudo);
    	    		
    	    		
    	    		if(!notif.isEmpty()){
    	    			String youHaveNewNotification = "you have some new NOTIFICATIONS, please read it !! <br> ";
    	    			
    	    					request.setAttribute("youHaveNewNotification", youHaveNewNotification);
    	    					   	    					
    	    		}
    	    		//fin gestion du voyant
    	  	    		
    	    		request.setAttribute("events", eventCreated);
    	    		request.setAttribute("invitatedEvents", invitationAccepted);
    	    		
    	    		//pour rester dans la contexte pseudo, je dois le faire suivre.
    	    		request.setAttribute("pseudo", pseudo);
    	    		
    	    		 List<Notification> notifbis = nDAO.findMyNotifications(pseudo);
						
			     		for(Notification item : notif){
			 	    			int id = item.getIdnotification();	    			
			 	    			String ev = item.getEventAbout();
			 	    			String me = item.getMessageAlert_Invitation();
			 	    			String us = item.getUserDestinatore();
			 	    			
			 	    			//supprimer tous les messages
			 	    			if(!me.equals("none")){ 
				    				//afficher le message "me"
				    				//messagesAlert_Invitation.add(me);
				    				nDAO.move(id);
				    				}
			     		}
    	    		
    	    		
    	    		
    	    		// this.getServletContext().getRequestDispatcher(forward).forward( request, response );
        	
        }
       
        request.getRequestDispatcher(forward).forward(request, response);
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Event event = new Event();
        
       
        
        String pseudo = request.getParameter("eventCreator");
        event.setEventCreator(pseudo);
        event.setIndoor_outdoor(request.getParameter("indoor_outdoor"));
        event.setName(request.getParameter("name"));
        event.setPlace(request.getParameter("place"));
        
        
        
        
      
        try {
            Date d = new SimpleDateFormat("MM/dd/yyyy").parse(request.getParameter("date"));
            event.setDate(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
       // pour updater l' évenement en question au cas ou 
        String eventid = request.getParameter("eventid");
        
        
        
       try{ 
        
        if(eventid == null || eventid.isEmpty())
        {
        	 //gestion de l'ajout des notifications
            // Evènement management...messageAllert about bad weather is managed altrove
            String[] userToBeNotified = request.getParameterValues("check");
            String eventAbout, messageAlert_Invitation, userDestinatore;
            for( String item: userToBeNotified){
            	userDestinatore = item;
            	messageAlert_Invitation = "none";
            	eventAbout = event.getName();
                nDAO.add(eventAbout, messageAlert_Invitation, userDestinatore);
                
            }
            
        	
        	
             eDAO.add(event); 
        	        	
        }
        
        
        else
        {          
        	try{
        	
        	int eventId = Integer.parseInt(eventid);
            eDAO.updateEvent(event, eventId); 
            
           } catch(EclipseLinkException e){
        	   // gestion du cas ou l user clicke sur submit prima di compilare tutto dans "insert"
        	   String forward = EDIT;
        	   
        	   String fdate = "mm/jj/yyyy";
               request.setAttribute("fdate", fdate);
               
               int eventId = Integer.parseInt(eventid);
               String mess = "you must fulfill all the containt correctly!!!!!" ;
               
               Event eventbisE = eDAO.getEventById(eventId);
               request.setAttribute("event", eventbisE);
               request.setAttribute("pseudo", pseudo);
               
               request.setAttribute("mess", mess);
               request.getRequestDispatcher(forward).forward(request, response);
           }
        }
        
       } catch(NullPointerException n){
    	   // gestion du cas ou l user clicke sur submit prima di compilare tutto dans "insert"
    	   String forward = INSERT;
    	   
    	   String fdate = "mm/jj/yyyy";
           request.setAttribute("fdate", fdate);
           
    	   String mess = "you must fulfill all the containt !!!!!" ;
           request.setAttribute("pseudo", pseudo);
           List<String> list = uDAO.findAll();
           request.setAttribute("listToInvite", list);
           request.setAttribute("mess", mess);
           request.getRequestDispatcher(forward).forward(request, response);
       }
       
       catch(DatabaseException e){
    	   // gestion du cas ou l user clicke sur submit prima di compilare tutto dans "insert"
    	   String forward = INSERT;
    	   
    	   String fdate = "mm/jj/yyyy";
           request.setAttribute("fdate", fdate);
           
    	   String mess = "you must fulfill all the containt correctly !!!!!" ;
           request.setAttribute("pseudo", pseudo);
           List<String> list = uDAO.findAll();
           request.setAttribute("listToInvite", list);
           request.setAttribute("mess", mess);
           request.getRequestDispatcher(forward).forward(request, response);
       }

       
     // puntare direttamente all pagina personale..vedremmo dopo !
  		
  		//les deux tables de la page personelle
  		List<Event> eventCreated = eDAO.findEventsCreator(pseudo);
  		List<Event> invitationAccepted = iDAO.findInvitationAccepted(pseudo);
  		
  	//calcolo della temperautra in °F per ogni Event   	    		
  		Map<Event, Long> tempsMaxE = new HashMap<Event,Long>();   
  		Map<Event,Long> tempsMinE = new HashMap<Event,Long>();
  		Map<Event, Long> tempsMaxI = new HashMap<Event,Long>();  
  		Map<Event, Long> tempsMinI = new HashMap<Event,Long>();
    	
        for( Event item: eventCreated){     
  			
        	float vet[]= getTemp(item.getPlace());
        	
        	tempsMaxE.put(item,(long)vet[0]);   
        	tempsMinE.put(item,(long)vet[1]);                    
          }              
  		
        for( Event item: invitationAccepted){
  			
            float vet[]= getTemp(item.getPlace());
        	         
        	 tempsMaxI.put(item,(long)vet[0]);                      
        	 tempsMinI.put(item,(long)vet[1]);    
        	 
          }
  		
  		//Temperatures
  		request.setAttribute("tempsMaxE", tempsMaxE);
  		request.setAttribute("tempsMinE", tempsMinE);
  		request.setAttribute("tempsMaxI", tempsMaxI);
  		request.setAttribute("tempsMinI", tempsMinI);
  		
  		
  		//gestion du voyant de notifications
  		List<Notification> notif = nDAO.findMyNotifications(pseudo);
  		if(!notif.isEmpty()){
  			String youHaveNewNotification = "you have some new NOTIFICATIONS, please read it !! <br> ";
  					request.setAttribute("youHaveNewNotification", youHaveNewNotification);
  			
  		}
  		//fin gestion du voyant
	    		
  		request.setAttribute("events", eventCreated);
  		request.setAttribute("invitatedEvents", invitationAccepted);
  		
  		//pour rester dans la contexte pseudo, je dois le faire suivre.
  		request.setAttribute("pseudo", pseudo);
  		
  		
  		
  		
  		
  		this.getServletContext().getRequestDispatcher("/WEB-INF/PersonalPage.jsp").forward( request, response );
    }

	
    public float[] getTemp(String place) throws IOException, MalformedURLException, JSONException{
  	  
    	
    	 OpenWeatherMap owm = new OpenWeatherMap(""); 		
 	     DailyForecast df = owm.dailyForecastByCityName(place, Byte.parseByte("5"));
 	     Forecast forecastList = df.getForecastInstance(1);
        Temperature temp = forecastList.getTemperatureInstance();
        DailyForecast.Forecast forecast = df.getForecastInstance(1);
        
        if (forecast.hasDateTime()) {
       float vet[] = {temp.getMaximumTemperature(), temp.getMinimumTemperature() };
        		return vet; 
        	}
		return null;
     }
	

}
